package xyz.xiangyushui.dao.user;

import java.util.List;
import java.util.Map;

import xyz.xiangyushui.dao.Dao;
import xyz.xiangyushui.javaBean.user.Role;
import xyz.xiangyushui.javaBean.user.User;

public class UserDao extends Dao{
	
	public User auth(String userName,String pwd){
		User user=new User();
		List<Object> users=db.excuteQuery("select * from user where userName=? and password=?", new Object[]{userName,pwd});
		if(users.isEmpty()){
			return null;
		}else{
			@SuppressWarnings("unchecked")
			Map<String,Object> results=(Map<String, Object>) users.get(0);
			user.setName((String)results.get("userName"));
			user.setRole(Role.getRole((int)results.get("role")));
		}
		return user;
	}
	
	public void add(User user){
		db.executeUpdate("insert into user values(?,?,?)", new Object[]{user.getName(),user.getPwd(),user.getRole().ordinal()});
	}
	
	public void delete(String userName){
		db.executeUpdate("delete from user where userName=?", new Object[]{userName});
	}
	
	public boolean exists(User u){
		List<Object> users=db.excuteQuery("select * from user where userName=?", new Object[]{u.getName()});
		return !users.isEmpty();
	}
	
	public void modifyPwd(String userName,String password){
		db.executeUpdate("update user set password=? where userName=?", new Object[] {password,userName});
	}
	
}
